import React from 'react'
import {
    Button,
    Table,
    Form,
    Row,
    Col,
    Input,
    Avatar,
    Modal,
    List,
    Collapse,
    Select,
    DatePicker,
    TreeSelect,
    Popconfirm, Icon,message,
} from 'antd';
import { connect } from 'dva';
import CommentModal from './CommentModal';
import './Comment.scss';
import { getTypeList } from '../../../services/typeFetch';
import { addAdminComment } from '../../../services/fetch';
import VideoButton from "../Video/VideoButton";

const { TextArea } = Input;
const Panel = Collapse.Panel;
const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const TreeNode = TreeSelect.TreeNode;
@connect(({ comment }) => ({
    comment: comment
}))
@connect(({ video }) => ({
    video,
}))
@Form.create()
export default class Comment extends React.PureComponent {

    constructor(props) {
        super(props);

        this.state = {
            typeList: [],
            sortInfo: {
                field:'',
                order:'',
            },
            isAggregation:false,
            isshowReplyModal:false,
            reply:'',
            pid:null,
            current_page:1,
            current_pageSize:10

        }

    }

    componentDidMount() {
        const { search } = window.location
        const paramsString = search.substring(1)
        const searchParams = new URLSearchParams(paramsString)
        if (searchParams.get('type')) {
            const type = searchParams.get('type')
            console.log(type)
            if (type === 'aggregation') {
                this.props.form.setFieldsValue({
                    status:'0'
                })
                this.setState({
                  isAggregation:true
                },()=>{
                    this.props.dispatch({
                        type: 'comment/getAllComment',
                        data: {
                            index: 1,
                            page_size: 10,
                            status:'0'
                        }
                    })
                })
            }
        }else{
             this.props.dispatch({
                        type: 'comment/getAllComment',
                        data: {
                            index: 1,
                            page_size: 10
                        }
                    })
        }
        console.log(this.props)
       
        this.getList()
    }
    /**
     * 获取分类 数据
     */
    getList=()=>{
        getTypeList().then((res)=>{
            let list = res.data.data;
            const data = []
            list.map((item, index) => {
                let obj = {
                    key: String(index),
                    plate_id: item.plate_id,
                    title: item.plate_name,
                    plate_name : item.plate_name,
                    children: item.children ? item.children : [],
                    value: item.plate_id,
                    disabled: item.children ? true : false
                }
                if (item.children) {
                    item.children.map((i, ins) => {
                        let obj2 = {
                            key: String(index) + '-' + ins,
                            plate_id: i.plate_id,
                            title: i.plate_name,
                            value: i.plate_id,
                            plate_name : i.plate_name,
                            template_id: i.template_id,
                        }
                        item.children[ins] = obj2
                    })
                }
                data[index] = obj
            })

            this.setState({
                typeList: data
            })
        })
    }

    search = () => {
        const { dispatch, form } = this.props;
        let sorter = this.state.sortInfo;
        form.validateFieldsAndScroll((err, values) => {
            this.props.dispatch({
                type: 'comment/getAllComment',
                data: {
                    index: 1,
                    page_size: 10,
                    information_title: values.information_title,
                    comment_content: values.comment_content,
                    start: values.time ? values.time[0] ? values.time[0].format('YYYY-MM-DD') + " 00:00:00" : '' : '',
                    end: values.time ? values.time[1] ? values.time[1].format('YYYY-MM-DD') + " 23:59:59" : '' : '',
                    status: values.status ? values.status : '',
                    plate_id: values.plate_id ? values.plate_id : '',
                    sortField: sorter.field ? sorter.field : '',
                    sortOrder: sorter.order ? sorter.order : ''

                }
            })
        });
    }

    comment_delete = (e) => {

        e.preventDefault();
    }

    handleTableChange = (paginations, filters, sorter) => {
        const { pagination } = this.props.comment;

        let sortField = sorter.field ? sorter.field : '';
        let sortOrder = sorter.order ? sorter.order : '';
        this.setState({
            sortInfo: {
                field:sortField,
                order:sortOrder,
            },
            current_page:paginations.current,
            current_pageSize:paginations.pageSize
        });

        let p = { ...pagination, index: paginations.current, page_size: paginations.pageSize,sortFiled:sortField,sortOrder:sortOrder };
        
        this.props.dispatch({
            type: 'comment/getAllComment',
            data: p
        })

        // this.search();

    }

    /**
     *  审批 删除 上下架
     */
    onSelectChange = (selectedRowKeys, data) => {
        // console.log(selectedRowKeys, data);
        let ids = [];
        data.forEach((item) => {
            ids.push(item.comment_id)
        })
        console.log(ids,'ids11');


        this.props.dispatch({
            type: 'comment/setSelectedPlateIds',
            data: {
                ids: ids,
                list: data
            }
        })
        this.props.dispatch({ type: 'comment/updateMoreDeal', data: selectedRowKeys });
    }

    showReplyModal = (record) => {
        console.log(record)
        this.setState({
            isshowReplyModal:true,
            pid:record.comment_id
        })
    }
    showReplyModalOk = () => {
        let params = {
            pid:this.state.pid,
            comment_content:this.state.reply
        }
        addAdminComment(params).then(res=>{
           if(res.data.code ==200){
               message.success('回复成功！')
                if(this.state.isAggregation){
                    this.props.dispatch({
                        type: 'comment/getAllComment',
                        data: {
                            index: this.state.current_page,
                            page_size: this.state.current_pageSize,
                            status:'0'
                        }
                    })
                }else{
                    this.props.dispatch({
                        type: 'comment/getAllComment',
                        data: {
                            index: 1,
                            page_size: this.state.current_pageSize
                        }
                    })
                }
            
           }else{
               message.error('回复失败！')
           }
           this.setState({
            isshowReplyModal:false,
            reply:''
        })
        })
       
    }
    showReplyModalCancel = () => {
        this.setState({
            isshowReplyModal:false,
            reply:''
        })
    }
    inputReply = (e) => {
        this.setState({
            reply:e.target.value
        })
    }

    render() {


        const columns = [{
            width:120,
            title: '会员名称',
            dataIndex: 'member_nickname',
            key: 'member_nickname',

        }, {
            width:60,
            title: '头像',
            dataIndex: 'head_pic',
            key: 'head_pic',
            render: (text) => {
                if (text) {
                    return <Avatar src={text} />
                } else {
                    return <Avatar icon="user" />
                }
            }
        }, {
            width:200,
            title: '评论内容',
            dataIndex: 'filter_comment_content',
            key: 'filter_comment_content',
            className:'comment-content',
            render: (text) => {
                return <div dangerouslySetInnerHTML={{ __html: text}}></div>
            }
        }, {

            title: '文章标题',
            dataIndex: 'information_title',
            key: 'information_title',
            render: (text, record) => {
                return <a onClick={() => {
                    this.props.dispatch({
                        type: 'comment/showModal',
                        payload: {
                            information_id: record.information_id,
                        }
                    })
                }}>{text}</a>
            }
        }, {
            width:190,
            title: '评论时间',
            dataIndex: 'create_time',
            key: 'create_time',
            sorter: true,

        }, {
            width:90,
            title: '点赞',
            dataIndex: 'like_count',
            key: 'like_count',
            sorter: true,
        }, {
            width:80,
            title: '敏感词',
            dataIndex: 'sensitive_words',
            key: 'sensitive_words',
            render: (words,record) => {
                return <span style={{ color: '#f44336' }}>{words}</span>;

            }
        }
        , {
            width:100,
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status,record) => {
                if (status === 0){
                    return <span style={{ color: '#607d8b' }}>待审核</span>
                }else if (status === 1){
                    return <span style={{ color: '#4caf50' }}>审核通过</span>
                }else{
                    return <span style={{ color: '#f44336' }}>拒审</span>
                }

            }
        },{
            width:150,
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => {
                console.log(record)
                return (
                    <div className={"action-list"}>

                    <span   onClick={() => {
                    this.props.dispatch({
                        type: 'comment/checkComment',
                        data: { comment_id: record.comment_id,status :1 }
                        })
                    }}>
                        <a href="javascript:;">审核通过</a>
                    </span>


                    <span  onClick={() => {
                    this.props.dispatch({
                        type: 'comment/checkComment',
                        data: { comment_id: record.comment_id,status :2 }
                        })
                    }}>
                        <a href="javascript:;">拒审</a>
                    </span>

                {record.pid == 0 ?
                <span  onClick={() => {
                    this.props.dispatch({
                        type: 'comment/showModal',
                        payload: {
                            information_id: record.information_id,
                            comment_id:record.comment_id,
                        },
                    })

                }}>

                <a href="javascript:;">回复详情</a>
                    </span>
                : ''}
                    <Popconfirm placement="leftTop" title='确定删除？'  icon={null}
                    onConfirm={()=>this.props.dispatch({
                    type: 'comment/deleteComment',
                    data: { comment_id: record.comment_id }
                 })} okText="确定" cancelText="取消">
                    <span>
                    <a href="javascript:;">删除</a>
                    </span>
                    </Popconfirm>
                    {record.status == 1 ?
                    <span onClick={()=>this.showReplyModal(record)}>
                    <a href="javascript:;">回复</a>
                </span>:''
                }
                    

                </div>
                )


            },

        }];

        const { getFieldDecorator } = this.props.form;
        const { dataSource, pagination } = this.props.comment;

        const total = pagination.total ? pagination.total : '';


        const selectedRowKeys = this.props.comment.selectedRowKeys;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <section className="Comment">
                <header className="header">
                    评论管理
                </header>
                <div className="content">
                    <div className="main">
                        <Row gutter={24}>
                            <Col span={6}>
                                <div className='btn_group' style={{margin:"10px"}}>
                                    <Button className='mon_btn' style={{marginRight:"15px"}} type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={() => {
                                        let ids = this.props.comment.selectedPlateIds;
                                        this.props.dispatch({
                                            type: 'comment/checkComment',
                                            data: { comment_id: ids.join(','),status :1 }
                                        });
                                        this.props.dispatch({ type: 'comment/updateMoreDeal', data: [] });

                                    }}>
                                        <Icon type="check" theme="outlined" />
                                        <span class='fs_15'>ᠬᠢᠨᠠᠨ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠪᠡ</span>
                                    </Button>

                                    <Button className='mon_btn' type="defualt" disabled={selectedRowKeys.length > 0 ? false : true} onClick={() => {
                                        let ids = this.props.comment.selectedPlateIds;
                                        this.props.dispatch({
                                            type: 'comment/checkComment',
                                            data: { comment_id: ids.join(','),status :2 }
                                        });
                                        this.props.dispatch({ type: 'comment/updateMoreDeal', data: [] });

                                    }}>
                                        <Icon type="check" theme="outlined" />
                                        <span class='fs_15 pt_10'>ᠬᠢᠨᠠᠨ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠭᠰᠡᠨ ᠦᠭᠡᠢ</span>
                                    </Button>
                                </div>
                            </Col>
                            <Col span={18}>
                                <div>
                                    <Form layout="inline" onSubmit={this.handleSubmit}>
                                        <FormItem mon_class='mon_label' mon_block='' label='ᠴᠠᠭ : ' >
                                            <div mon_class='mon_range_picker'>
                                                {getFieldDecorator('time')(
                                                    <RangePicker placeholder={['ᠡᠬᠢᠯᠡᠬᠦ ᠴᠠᠭ', 'ᠲᠡᠭᠦᠰᠬᠦ ᠴᠠᠭ']} />
                                                )}
                                            </div>
                                        </FormItem>

                                        <FormItem mon_class='mon_label' mon_block='' label="ᠵᠣᠬᠢᠶᠠᠯ᠎ᠤᠨ ᠭᠠᠷᠴᠠᠭ : ">
                                            {getFieldDecorator('information_title', {
                                                initialValue: ''
                                            })(
                                                <Input mon_class='mon_input' className='h_155' placeholder=""/>
                                            )}
                                        </FormItem>

                                        <FormItem mon_class='mon_label' mon_block='' label="ᠱᠢᠭᠦᠮᠵᠢ᠎ᠶᠢᠨ ᠠᠭᠤᠯᠭ᠎ᠠ : ">
                                            {getFieldDecorator('comment_content', {
                                            initialValue: ''
                                            })(
                                            <Input mon_class='mon_input' className='h_155' placeholder=""/>
                                            )}
                                        </FormItem>
                                        <FormItem mon_class='mon_label' mon_block='' label='ᠲᠥᠯᠦᠪ : '>
                                            <div mon_class='mon_select'>
                                                {getFieldDecorator('status',{initialValue:this.state.isAggregation?'0':''})(
                                                    <Select>
                                                        <Option value="0">ᠬᠢᠨᠠᠬᠤ ᠪᠡᠷ ᠪᠠᠢᠭ᠎ᠠ</Option>
                                                        <Option value="1">ᠬᠢᠨᠠᠨ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠪᠡ</Option>
                                                        <Option value="2">ᠬᠢᠨᠠᠨ ᠵᠥᠪᠰᠢᠶᠡᠷᠡᠭᠰᠡᠨ ᠦᠭᠡᠢ</Option>
                                                    </Select>
                                                )}
                                            </div>
                                        </FormItem>

                                        <FormItem
                                            mon_class='mon_label'
                                            mon_block=''
                                            label="ᠮᠡᠳᠡᠭᠡ ᠵᠠᠩᠭᠢ᠎ᠶᠢᠨ ᠨᠢᠭᠤᠷ : "
                                            style={{width:"230px"}}
                                        >
                                            <div mon_class='mon_select'>
                                                {getFieldDecorator('plate_id')(
                                                    <TreeSelect style={{width:"130px"}}
                                                        dropdownStyle={{ maxHeight: 400 }}
                                                        dropdownMatchSelectWidth
                                                        treeDefaultExpandAll
                                                        allowClear
                                                    >
                                                        {this.state.typeList.map((item) => {
                                                            let children = item.children ? item.children : [];
                                                            return (
                                                                <TreeNode disabled={children.length > 0 ? true : false} value={item.plate_id} title={item.plate_name} key={item.plate_id}>
                                                                    {children.map((item2) => {
                                                                        return <TreeNode value={item2.plate_id} title={item2.plate_name} key={item2.plate_id} />
                                                                    })}
                                                                </TreeNode>
                                                            )
                                                        })}
                                                    </TreeSelect>
                                                )}
                                            </div>
                                        </FormItem>

                                        <FormItem>
                                            <Button
                                                type="primary"
                                                className='mon_btn ml_10'
                                                style={{
                                                    marginRight: '20px'
                                                }}
                                                onClick={this.search}
                                            >ᠬᠠᠢᠬᠤ</Button>
                                            <Button
                                                className='mon_btn'
                                                onClick={() => {
                                                    this.props.form.resetFields();
                                                    this.search()
                                                }}
                                            >ᠠᠷᠢᠯᠭᠠᠬᠤ</Button>
                                        </FormItem>
                                    </Form>
                                </div>
                            </Col>
                        </Row>
                        
                        <Table
                            className="table-antd"
                            dataSource={dataSource}
                            columns={columns}
                            onChange={this.handleTableChange}
                            // pagination={{
                            //     current: pagination.current,
                            //     pageSize: pagination.pageSize,
                            //     total: pagination.total,
                            //     showTotal: (total) => {  //设置显示一共几条数据
                            //         return `共有${total}数据`
                            //     }
                            //
                            // }}
                            rowSelection={rowSelection}
                            // loading={this.props.comment.loading}

                            style={{ marginTop: '10px' }}
                            pagination={{
                                total: total, //数据总数量
                                size: 'small',
                                showQuickJumper: true,
                                current: pagination.current ? pagination.current : 1,
                                pageSize: pagination.page_size,  //显示几条一页
                                defaultPageSize: 10, //默认显示几条一页
                                showSizeChanger: true,  //是否显示可以设置几条一页的选项
                                onShowSizeChange: (current, size) => {

                                    // if(size >= videoData.total){
                                    //     index = 1;
                                    // }
                                    let p = { ...pagination, index: current, page_size: size };
                                    this.props.dispatch({
                                        type: 'comment/getAllComment',
                                        data: p
                                    })
                                },
                                pageSizeOptions: ['10', '25', '50', '75', '100'],
                                style: { marginRight: '50px' },
                                showTotal: (total) => {  //设置显示一共几条数据
                                    return `共有${total}数据`
                                },

                                onChange: (page,pageSize) => {



                                    this.props.dispatch({ type: 'comment/updateMoreDeal', data: [] });
                                    this.props.dispatch({
                                        type: 'comment/setSelectedPlateIds',
                                        data: {
                                            ids: [],
                                            list: []
                                        }
                                    })
                                    let p = { ...pagination, index: page, page_size: pageSize };
                                    this.props.dispatch({
                                        type: 'comment/getAllComment',
                                        data: p
                                    })


                                }
                            }}/>
                    </div>
                </div>
                <CommentModal />
                <Modal
                title="回复评论"
                visible={this.state.isshowReplyModal}
                onOk={this.showReplyModalOk}
                onCancel={this.showReplyModalCancel}
                okText="确认"
                cancelText="取消">
                   <div style={{display:'flex'}}>
                   <span style={{flex:'20%'}}>回复详情：</span>
                   <TextArea rows={4} value={this.state.reply} onInput={this.inputReply}/>
                    </div> 
                </Modal>
            </section>
        )
    }
}
